package com.example.articleservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.articleservice.entity.Category;
import com.example.articleservice.service.ICategoryService;
import com.example.common.Result;
import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Mr.Tang
 * @since 2024-06-21
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private ICategoryService categoryService;

    @PostMapping("/add")
    public Result add(Category category) {
        // 1. 非空校验
        if (category ==null || !StringUtils.hasLength(category.getName())) {
            return Result.fail(-1,"非法参数!");
        }

        // 2. 调用service
        boolean ret = categoryService.save(category);

        // 3. 结果返回给前端
        if (!ret) {
            return Result.fail(-1,"服务发生错误");
        }
        return Result.success();
    }


    @GetMapping("/list")
    public Result list() {
        List<Category> list = categoryService.list(new QueryWrapper<Category>().orderByDesc("cid"));
        return Result.success(list);
    }


    @PostMapping("/del")
    public Result del(Integer cid) {
        // 1. 参数校验
        if (cid == null || cid <= 0) {
            return Result.fail(-1, "非法参数");
        }

        // 2. 调用service
        boolean ret = categoryService.removeById(cid);
        if (!ret) {
            return Result.fail(-1, "服务发生错误");
        }

        // 3. 成功返回
        return Result.success();
    }

}
